package com.example.gokchinesefoodmappcdev.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.gokchinesefoodmappcdev.entity.GoodsInfoExcel;
import com.example.gokchinesefoodmappcdev.entity.PageBean;
import com.example.gokchinesefoodmappcdev.entity.dto.GoodsDTO;
import com.example.gokchinesefoodmappcdev.entity.dto.GoodsInfoAndGoodsSkuDTO;
import com.example.gokchinesefoodmappcdev.entity.dto.GoodsInfoExcelDTO;
import com.example.gokchinesefoodmappcdev.entity.dto.UpdateGoodsDTO;
import com.example.gokchinesefoodmappcdev.service.*;
import com.example.gokchinesefoodmappcdev.util.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@RestController
public class GoodsController {



    @Autowired
    GoodsInfoService goodsInfoService;
    @Autowired
    GoodsPicService goodsPicService;
    @Autowired
    GoodsSkuService goodsSkuService;
    @Autowired
    GoodsAttrKeyService goodsAttrKeyService;
    @Autowired
    GoodsAttrValService goodsAttrValService;

    /*
    * 增加商品信息
    * */
    @RequestMapping("/rest/goods/save")
    public Map<String,Object> save(GoodsDTO goodsInfo){

        ResultData resultData = goodsInfoService.insertGoodsInfo(goodsInfo);
        Integer goodId = goodsInfoService.selectGoodsIdByGoodCode(goodsInfo);
        goodsPicService.insertGoodsPic(goodId,goodsInfo);
        goodsAttrKeyService.insertGoodsAttrKey(goodId, goodsInfo);
        Integer attrKeyId = goodsAttrKeyService.selectAttrKeyIdByGoodIdAndAttrName(goodId, goodsInfo);
        goodsAttrValService.insertAttrVal(attrKeyId, goodId, goodsInfo);
        goodsSkuService.insertSkuInfo(goodId, goodsInfo);

        return resultData;
    }

    /*
    * 查询商品信息列表（根据分页条件）
    * */
    @RequestMapping("/rest/goods/list")
    public Map<String,Object> selectGoodSList(int pageSize,int pageNumber){

        ResultData resultData = goodsInfoService.selectGoodsList(pageSize, pageNumber);
        return resultData;

    }

    /*
     * 根据ID查询商品信息
     * */
    @RequestMapping("/rest/goods/info")
    public Map<String,Object> selectGoodsInfoById(int id){

        ResultData resultData = goodsInfoService.selectGoodsInfoById(id);
        return resultData;

    }
    /*
     * 根据传入的ID数组，删除对应的商品
     * */
    @RequestMapping("/rest/goods/remove")
    public Map<String,Object> removeGoods(@RequestBody Integer[] ids){

        ResultData resultData=null;
        List<Integer> goodIds = (List<Integer>) Arrays.asList(ids);
        for (int i = 0; i < goodIds.size(); i++) {
            resultData = goodsInfoService.removeGoodById(goodIds.get(i));
        }

        return resultData;

    }
    /*
     * 修改商品信息
     * */
    @RequestMapping("/rest/goods/update")
    public Map<String,Object> updateGoodsInfo(@RequestBody UpdateGoodsDTO goodsDTO){

        ResultData resultData = goodsInfoService.updateGoodsInfo(goodsDTO);

        //获取商品ID
        Integer goodId = goodsDTO.getId();
        //根据商品ID查询对应的skuPath（也就是图片的原始地址）
        String skuPath = goodsSkuService.selectPicPathByGoodId(goodId);
        //根据图片原始地址和商品ID，查出图片Id，方便与后续的根据图片ID修改图片
        int id = goodsPicService.selectIdByGoodIdAndSkuPath(goodId, skuPath);
        System.out.println(id);

        goodsDTO.getPictures().forEach(g->{
            String picPath = g.getPicPath();
        //根据图片ID修改图片
            goodsPicService.updatePicInfoByIdAndPicPath(id, picPath);
            goodsSkuService.updateSkuPicByGoodIdAndPicPath(goodId, picPath);
        });

        //修改sku信息
        goodsDTO.getSpecifications().forEach(s->{
            goodsSkuService.updateSkuInfo(s.getId(), s.getPrice(), s.getStock(), s.getWeight());
        });

        return resultData;

    }

    /*
     * 修改商品上架状态
     * */
    @RequestMapping("/rest/goods/updateOnSale")
    public Map<String,Object> updateGoodsOnSale(int id,String onSale){

        ResultData resultData = goodsInfoService.updateGoodsOnSale(id, onSale);
        return resultData;
    }

    /*
     * 商品导出（excel表格）
     * */
    @RequestMapping("/rest/goods/listToExcel")
    public Map<String,Object> listToExcel(HttpServletResponse response){

        ExcelWriter writer = null;
        OutputStream out = null;
        try {
            List<GoodsInfoExcelDTO> goodsInfo = goodsInfoService.getGoodsInfo();
            String fileName = "商品信息表格";
            out = new FileOutputStream("F:\\var\\" + fileName + ".xlsx");
            writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
            Sheet sheet = new Sheet(1, 0, GoodsInfoExcel.class);
            sheet.setSheetName("商品信息");
            writer.write(goodsInfo, sheet);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.finish();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        ResultData resultData = new ResultData(ResultData.OPERATION_SUCCESS, "导出成功,地址为：F\\var");
        return resultData;


    }
    /**
     * 分页查询
     * 根据条件查询所有商品
     * @param goodsInfoAndGoodsSkuDTO
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/rest/goods/listReviews")
    public PageBean<GoodsInfoAndGoodsSkuDTO> selectGoodsAll(GoodsInfoAndGoodsSkuDTO goodsInfoAndGoodsSkuDTO, int pageNum, int pageSize) {
        PageBean<GoodsInfoAndGoodsSkuDTO> goodsAll = goodsInfoService.selectGoodsAll(goodsInfoAndGoodsSkuDTO, pageNum, pageSize);
        return goodsAll;
    }
    /**
     * 根据id查询商品详情
     * @param goodsInfoAndGoodsSkuDTO
     * @return
     */
    @RequestMapping("/rest/goods/goodsinfo")
    public ResultData selectGoodsAndAttrKeyAndAttrValAndPicAndSku(GoodsInfoAndGoodsSkuDTO goodsInfoAndGoodsSkuDTO) {
        ResultData resultData = goodsInfoService.selectGoodsAndAttrKeyAndAttrValAndPicAndSku(goodsInfoAndGoodsSkuDTO);
        return resultData;
    }
    @RequestMapping("/rest/goods/review")
    public ResultData updateGoodsInfoReviewStatusById(int id, String reviewRet) {
        ResultData resultData = goodsInfoService.updateGoodsInfoReviewStatusById(id, reviewRet);
        return resultData;
    }




}
